//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Eas.WebCrawler.Common.IO {
    /// <summary>Used to write text to a simple text file without holding a continuous lock on the file..</summary>
    public class LogFileWriter {
        /// <summary>The name of the log file being written to.</summary>
        /// <remarks>Backing field for the FileName property.</remarks>
        /// <seealso cref="FileName"/>
        private string _FileName;

        /// <summary>The name of the log file being written to.</summary>
        public string FileName {
            get { return _FileName; }
        }

        /// <summary>Constructs a <see cref="LogFileWriter"/> from the name of the file to which entries should be written.</summary>
        /// <param name="fileName">The name of the file to which entries should be written.</param>
        public LogFileWriter(string fileName) { _FileName = fileName; }

        /// <summary>Writes the specified formatted string to the log file.</summary>
        /// <param name="format">The base format string to write out to the log file.</param>
        /// <param name="parameters">The parameters to use in writting.</param>
        /// <remarks>This function formats your string via a call to <see cref="string.Format(string, object)"/>.</remarks>
        public void Write(string format, params object[] parameters){
            WriteInternal(_FileName, false, format, parameters);
        }

        /// <summary>Writes the specified formatted string and a new line to the log file.</summary>
        /// <param name="format">The base format string to write out to the log file.</param>
        /// <param name="parameters">The parameters to use in writting.</param>
        /// <remarks>This function formats your string via a call to <see cref="string.Format(string, object)"/>.</remarks>
        public void WriteLine(string format, params object[] parameters) {
            WriteInternal(_FileName, true, format, parameters);
        }

        private static void WriteInternal(string fileName, bool writeLine, string format, object[] parameters) {
            if (parameters.Length > 0)
                format = string.Format(System.Globalization.CultureInfo.InvariantCulture, format, parameters);
            using (TextWriter writer = new System.IO.StreamWriter(fileName, true)) {
                if (writeLine)
                    writer.WriteLine(format);
                else
                    writer.Write(format);
            }
        }

    }
}
